﻿/**
 @Name：核心模块
 @Author：蓝博
 */

layui.define(['layer', 'setter', 'laytpl', 'view'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        setter = layui.setter,
        laytpl = layui.laytpl,
        view = layui.view,
        admin = {
            //Ajax请求
            req: view.req,
            //视图模块接口
            view: view,
            //路由处理
            router: view.router,
            //显示加载动画
            showLoading: view.showLoading,
            //移除加载动画
            removeLoading: view.removeLoading,
            //弹窗
            popup: view.popup,
            //提示弹窗
            popupTips: view.popupTips,
            //右侧弹窗
            popupRight: view.popupRight,
            //关闭当前iframe层弹窗
            closeThisDialog: view.closeThisDialog,
            //关闭非iframe类型的弹窗
            closeDialog: view.closeDialog,
            //让当前的ifram弹层自适应高度
            iframeAuto: view.iframeAuto,
            //绑定表单弹窗
            modelForm: view.modelForm,
            //获取弹窗数据
            getLayerData: view.getLayerData,
            //放入弹窗数据
            putLayerData: view.putLayerData,
            //loading按钮
            btnLoading : function (elem, text, loading) {
                if (text !== undefined && (typeof text == 'boolean')) {
                    loading = text;
                    text = undefined;
                }
                (text === undefined) && (text = '加载中');
                (loading === undefined) && (loading = true);
                if (loading) {
                    $(elem).addClass('ew-btn-loading');
                    $(elem).prepend('<span class="ew-btn-loading-text"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>' + text + '</span>');
                    $(elem).prop('disabled', 'disabled');
                } else {
                    $(elem).removeClass('ew-btn-loading');
                    $(elem).children('.ew-btn-loading-text').remove();
                    $(elem).removeProp('disabled', 'disabled');
                }
            },
            //表格单元格超出内容自动展开
            openCellAutoExpand: function () {
                $('body').off('mouseenter.openCellAutoExpand').on('mouseenter.openCellAutoExpand', '.layui-table-view td', function () {
                    $(this).find('.layui-table-grid-down').trigger('click');
                }).off('mouseleave.openCellAutoExpand').on('mouseleave.openCellAutoExpand', '.layui-table-tips>.layui-layer-content', function () {
                    $('.layui-table-tips-c').trigger('click');
                });
            },
            //写入缓存临时数据
            putTempData: function (key, value) {
                var tableName = setter.tableName + '_tempData';
                if (value === undefined || value === null) {
                    layui.sessionData(tableName, { key: key, remove: true });
                } else {
                    layui.sessionData(tableName, { key: key, value: value });
                }
            },
            //获取缓存临时数据
            getTempData: function (key) {
                var tableName = setter.tableName + '_tempData';
                var tempData = layui.sessionData(tableName);
                return tempData ? tempData[key] : undefined;
            },
            //设置导航栏选中
            activeNav: function (url) {
                if (!url) {
                    url = location.hash;
                }
                if (url && url != '') {
                    $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav .layui-nav-item .layui-nav-child dd.layui-this').removeClass('layui-this');
                    $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav .layui-nav-item.layui-this').removeClass('layui-this');
                    var navDom = $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav a[lay-href="' + url + '"]');
                    if (navDom && navDom.length > 0) {
                        if ($('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav').attr('lay-accordion') == 'true') {  //手风琴效果
                            var pChilds = navDom.parent('dd').parents('.layui-nav-child');
                            $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav .layui-nav-itemed>.layui-nav-child').not(pChilds).css('display', 'none');
                            $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav .layui-nav-itemed').not(pChilds.parent()).removeClass('layui-nav-itemed');
                        }
                        navDom.parent().addClass('layui-this');  //选中当前
                        var asParents = navDom.parent('dd').parents('.layui-nav-child').parent();
                        asParents.not('.layui-nav-itemed').children('.layui-nav-child').css('display', 'block');
                        asParents.addClass('layui-nav-itemed');  //展开所有父级
                    }
                }
            },
            //获取浏览器高度
            getPageHeight: function () {
                return document.documentElement.clientHeight || document.body.clientHeight;
            },
            //获取浏览器宽度
            getPageWidth: function () {
                return document.documentElement.clientWidth || document.body.clientWidth;
            },
            //检查是否属于独立页面
            indPage: function (pathURL) {
                var isIndPage = false;
                layui.each(setter.indPage, function (index, item) {
                    if (pathURL === item) {
                        return isIndPage = true;
                    }
                });
                return isIndPage;
            },
            //禁用浏览器前进后退
            history: function () {
                if (window.history && window.history.pushState) {
                    $(window).on('popstate', function () {
                        window.history.pushState('forward', null, location.hash);
                        window.history.forward(1);

                    });
                }
                window.history.pushState('forward', null, location.hash);
                window.history.forward(1);
            },
            //路由不存在处理
            notFound: function () {
                var pathURL = location.hash.substr(1);
                if (admin.indPage(pathURL)) {
                    admin.view(setter.layoutDom).render(pathURL);
                    admin.history();
                } else {
                    layer.alert('路由' + pathURL + '不存在', {
                        title: '提示',
                        skin: 'layui-layer-admin',
                        offset: '30px',
                        anim: 6,
                        shadeClose: true
                    });
                }
            },
            //注册路由
            regRouter: function (menus) {
                $.each(menus, function (index, item) {
                    if (item.url) {
                        admin.router.reg("#" + item.url, function (info) {
                            info.name = item.name;
                            info.iframe = item.iframe;
                            admin.changeView(info);
                        });
                    }
                    if (item.subMenus) {
                        admin.regRouter(item.subMenus);
                    }
                });
            },
            //处理路由改变
            changeView: function (info) {
                admin.activeNav(info.href); //设置导航栏选中
                admin.renderView(info, ".layui-layout-admin>.layui-body"); //渲染内容页面
            },
            //渲染组件
            renderView: function (info, contentDom) {
                admin.view(contentDom).render(info.path.join('/')).done(function () {
                    if (info.href != setter.viewDefault.entry && $("#breadcrumb").html() != undefined) {
                        laytpl($("#breadcrumb").html()).render(info, function (html) {
                            $(contentDom).prepend(html);
                        });
                    }
                }).error(function (res) {
                    if (res.xhr.status == 404) {
                        admin.router.notFound && admin.router.notFound(info);
                    }
                });
            },
            //获取面包屑
            getBreadcrumb : function (hash) {
                var breadcrumb = [];
                var href = $('.layui-layout-admin>.layui-side>.layui-side-scroll').find('[lay-href="' + hash + '"]');
                breadcrumb.push(href.text().replace(/(^\s*)|(\s*$)/g, ''));
                while (true) {
                    href = href.parent('dd').parent('dl').prev('a');
                    if (href.length === 0) {
                        break;
                    }
                    breadcrumb.unshift(href.text().replace(/(^\s*)|(\s*$)/g, ''));
                }
                return breadcrumb;
            },
            //加载主页
            loadHome: function (data) {
                admin.regRouter([data]);
                //初始化路由
                admin.router.init({ index: data.url, notFound: admin.notFound });
            },
            //跳转页面
            go: function (hash) {
                admin.router.go(hash);
            },
            //获取hash路径
            getHashPath: function (hash) {
                if (!hash || typeof hash === 'string') {
                    return admin.router.routerInfo(hash).path.join('/');
                }
                return hash.path.join('/');
            },
            //页面刷新
            refresh: function (url) {
                view.router.refresh(url);
            },
            //页面全屏
            full: function () {
                var ac = 'layui-icon-screen-full', ic = 'layui-icon-screen-restore';
                var $ti = $(this).find('i');
                var isFullscreen = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || false;
                if (isFullscreen) {
                    var efs = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
                    if (efs) {
                        efs.call(document);
                    } else if (window.ActiveXObject) {
                        var ws = new ActiveXObject('WScript.Shell');
                        ws && ws.SendKeys('{F11}');
                    }
                    $ti.addClass(ac).removeClass(ic);
                } else {
                    var el = document.documentElement;
                    var rfs = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen || el.msRequestFullscreen;
                    if (rfs) {
                        rfs.call(el);
                    } else if (window.ActiveXObject) {
                        var wss = new ActiveXObject('WScript.Shell');
                        wss && wss.SendKeys('{F11}');
                    }
                    $ti.addClass(ic).removeClass(ac);
                }
            },
            //页面锁屏
            lock: function () {
                var loadIndex = layer.load(2);
                view("body").render('/tpl/lock-screen').done(function (res) {
                    layer.close(loadIndex);
                });
            },
            //事件监听
            on : function (events, callback) {
                return layui.onevent.call(this, setter.modName, events, callback);
            },
            //打开消息
            message: function () {
                view.popupRight({
                    id: 'layer-message',
                    url: setter.viewDefault.message
                });
            },
            //打开便签
            note: function () {
                view.popupRight({
                    id: 'layer-note',
                    url: setter.viewDefault.note
                });
            },
            //打开关于
            author: function () {
                view.popupRight({
                    id: 'layer-author',
                    url: setter.viewDefault.author
                });
            },
            //个人中心
            info: function () {
                view.popupRight({
                    id: 'layer-info',
                    url: '/tpl/note'
                });
            },
            //修改密码
            psw: function () {
                view.popup({
                    id: 'layer-psw',
                    title: '修改密码',
                    shade: 0,
                    url: setter.viewDefault.password
                });
            },
            //安全退出
            logout: function () {

            },
            //工具类
            util: {
                //百度地图坐标转高德地图坐标
                convertBaiduAmap: function (point) {
                    var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
                    var x = point.lng - 0.0065,
                        y = point.lat - 0.006;
                    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
                    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
                    point.lng = z * Math.cos(theta);
                    point.lat = z * Math.sin(theta);
                    return point;
                },
                //高德地图坐标转百度地图坐标
                convertAmapBaidu: function (point) {
                    var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
                    var x = point.lng, y = point.lat;
                    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
                    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
                    point.lng = z * Math.cos(theta) + 0.0065;
                    point.lat = z * Math.sin(theta) + 0.006;
                    return point;
                },
                //动态数字
                animateNum: function (elem, isThd, delay, grain) {
                    isThd = isThd === null || isThd === undefined || isThd === true || isThd === 'true';  // 是否是千分位
                    delay = isNaN(delay) ? 500 : delay;   // 动画延迟
                    grain = isNaN(grain) ? 100 : grain;   // 动画粒度
                    var getPref = function (str) {
                        var pref = '';
                        for (var i = 0; i < str.length; i++) if (!isNaN(str.charAt(i))) return pref; else pref += str.charAt(i);
                    }, getSuf = function (str) {
                        var suf = '';
                        for (var i = str.length - 1; i >= 0; i--) if (!isNaN(str.charAt(i))) return suf; else suf = str.charAt(i) + suf;
                    }, toThd = function (num, isThd) {
                        if (!isThd) return num;
                        if (!/^[0-9]+.?[0-9]*$/.test(num)) return num;
                        num = num.toString();
                        return num.replace(num.indexOf('.') > 0 ? /(\d)(?=(\d{3})+(?:\.))/g : /(\d)(?=(\d{3})+(?:$))/g, '$1,');
                    };
                    $(elem).each(function () {
                        var $this = $(this);
                        var num = $this.data('num');
                        if (!num) {
                            num = $this.text().replace(/,/g, '');  // 内容
                            $this.data('num', num);
                        }
                        var flag = 'INPUT,TEXTAREA'.indexOf($this.get(0).tagName) >= 0;  // 是否是输入框
                        var pref = getPref(num.toString());
                        var suf = getSuf(num.toString());
                        var strNum = num.toString().replace(pref, '').replace(suf, '');
                        if (isNaN(strNum * 1) || strNum === '0') {
                            flag ? $this.val(num) : $this.html(num);
                            console.error('not a number');
                            return;
                        }
                        var int_dec = strNum.split('.');
                        var deciLen = int_dec[1] ? int_dec[1].length : 0;
                        var startNum = 0.0, endNum = strNum;
                        if (Math.abs(endNum * 1) > 10) startNum = parseFloat(int_dec[0].substring(0, int_dec[0].length - 1) + (int_dec[1] ? '.0' + int_dec[1] : ''));
                        var oft = (endNum - startNum) / grain, temp = 0;
                        var mTime = setInterval(function () {
                            var str = pref + toThd(startNum.toFixed(deciLen), isThd) + suf;
                            flag ? $this.val(str) : $this.html(str);
                            startNum += oft;
                            temp++;
                            if (Math.abs(startNum) >= Math.abs(endNum * 1) || temp > 5000) {
                                str = pref + toThd(endNum, isThd) + suf;
                                flag ? $this.val(str) : $this.html(str);
                                clearInterval(mTime);
                            }
                        }, delay / grain);
                    });
                },
                //深度克隆对象
                deepClone: function (obj) {
                    var result;
                    var oClass = admin.util.isClass(obj);
                    if (oClass === 'Object') {
                        result = {};
                    } else if (oClass === 'Array') {
                        result = [];
                    } else {
                        return obj;
                    }
                    for (var key in obj) {
                        if (!obj.hasOwnProperty(key)) continue;
                        var copy = obj[key];
                        if (admin.util.isClass(copy) === 'Object') {
                            result[key] = arguments.callee(copy); // 递归调用
                        } else if (admin.util.isClass(copy) === 'Array') {
                            result[key] = arguments.callee(copy);
                        } else {
                            result[key] = obj[key];
                        }
                    }
                    return result;
                },
                //判断富文本是否为空
                fullTextIsEmpty: function (text) {
                    if (!text) {
                        return true;
                    }
                    var noTexts = ['img', 'audio', 'video', 'iframe', 'object'];
                    for (var i = 0; i < noTexts.length; i++) {
                        if (text.indexOf('<' + noTexts[i]) > -1) {
                            return false;
                        }
                    }
                    var str = text.replace(/\s*/g, '');  // 去掉所有空格
                    if (!str) {
                        return true;
                    }
                    str = str.replace(/&nbsp;/ig, '');  // 去掉所有&nbsp;
                    if (!str) {
                        return true;
                    }
                    str = str.replace(/<[^>]+>/g, '');   // 去掉所有html标签
                    return !str;
                },
                //移除元素的style
                removeStyle: function (elem, options) {
                    if (typeof options === 'string') {
                        options = [options];
                    }
                    $(elem).each(function () {
                        try {
                            var arr = $(this).attr('style').split(';');
                            var style = '';
                            for (var i = 0; i < arr.length; i++) {
                                if (!$.trim(arr[i])) {
                                    continue;
                                }
                                var add = true;
                                var att = $.trim(arr[i].split(':')[0]);
                                for (var j = 0; j < options.length; j++) {
                                    if (!$.trim(options[j]) || att === $.trim(options[j])) {
                                        add = false;
                                        break;
                                    }
                                }
                                if (add) {
                                    style += $.trim(arr[i]) + ';';
                                }
                            }
                            $(this).attr('style', style);
                        } catch (e) {
                        }
                    });
                },
                //判断是否有权限
                hasPerm : function (auth) {
                    var auth = setter.getUserAuths();
                    if (auth) {
                        for (var i = 0; i < auth.length; i++) {
                            if (auth == auth[i]) {
                                return true
                            }
                        }
                    }
                    return false
                },
                //移除没有权限的元素
                renderPerm : function () {
                    $('[perm-show]').each(function () {
                        var auth = $(this).attr('perm-show');
                        if (!admin.hasPerm(auth)) {
                            $(this).remove();
                        }
                    });
                }
            }
        },
        layEvents = {
            //页面刷新
            refresh: function () {
                admin.refresh();
            },
            //页面全屏
            full: function () {
                admin.full();
            },
            //页面锁屏
            lock: function () {
                admin.lock();
            },
            //打开消息
            message: function () {
                admin.message();
            },
            //打开便签
            note: function () {
                admin.note();
            },
            //打开关于
            author: function () {
                admin.author();
            },
            //个人中心
            info: function () {
                admin.info();
            },
            //修改密码
            psw: function () {
                admin.psw();
            },
            //安全退出
            logout: function () {
                admin.logout();
            }
        }

    //侧导航折叠状态下鼠标经过无限悬浮效果
    $(document)
        .on('mouseenter', '.layui-layout-admin>.layui-side .layui-nav .layui-nav-item,.layui-layout-admin>.layui-side .layui-nav .layui-nav-item .layui-nav-child>dd', function () {
            if ($(this).find('>.layui-nav-child').length > 0) {
                $(this).addClass('admin-nav-hover');
                $(this).find('>.layui-nav-child').css('left', $(this).offset().left + $(this).outerWidth());
                var top = $(this).offset().top;
                if (top + $(this).find('>.layui-nav-child').outerHeight() > admin.getPageHeight()) {
                    top = top - $(this).find('>.layui-nav-child').outerHeight() + $(this).outerHeight();
                    (top < 60) && (top = 60);
                    $(this).find('>.layui-nav-child').addClass('show-top');
                }
                $(this).find('>.layui-nav-child').css('top', top).addClass('ew-anim-drop-in');
            } else if ($(this).hasClass('layui-nav-item')) {
                var tipText = $(this).find('cite').text();
                layer.tips(tipText, $(this), {
                    tips: [2, '#303133'], time: -1, success: function (layero, index) {
                        $(layero).css('margin-top', '12px');
                    }
                });
            }
        })
        .on('mouseleave', '.layui-layout-admin>.layui-side .layui-nav .layui-nav-item,.layui-layout-admin>.layui-side .layui-nav .layui-nav-item .layui-nav-child>dd', function () {
            layer.closeAll('tips');
            $(this).removeClass('admin-nav-hover');
            $(this).find('>.layui-nav-child').removeClass('show-top ew-anim-drop-in').css({ 'left': 'unset', 'top': 'unset' });
        });

    /* 所有lay-tips处理 */
    $(document)
        .on('mouseenter', '*[lay-tips]', function () {
            layer.tips($(this).attr('lay-tips'), this, {
                tips: [$(this).attr('lay-direction') || 1, $(this).attr('lay-bg') || '#303133'], time: -1, success: function (layero, index) {
                    if ($(this).attr('lay-offset')) {
                        $(this).attr('lay-offset') = $(this).attr('lay-offset').split(',');
                        var top = $(this).attr('lay-offset')[0], left = $(this).attr('lay-offset').length > 1 ? $(this).attr('lay-offset')[1] : undefined;
                        top && ($(layero).css('margin-top', top));
                        left && ($(layero).css('margin-left', left));
                    }
                }
            });
        })
        .on('mouseleave', '*[lay-tips]', function () {
            layer.closeAll('tips');
        });

    //页面跳转
    $(document).on('click', '*[lay-href]', function () {
        location.hash = $(this).attr('lay-href');
    });

    //所有ew-event
    $(document).on('click', '*[lay-event]', function () {
        var te = layEvents[$(this).attr('lay-event')];
        te && te.call(this, $(this));
    });

    /* 表单搜索展开更多 */
    $(document).on('click', '.form-search-expand', function () {
        if ($(this).data('expand') === true) {
            $(this).data('expand', false);
            $(this).html('收起 <i class="layui-icon layui-icon-up"></i>');
            var $elem = $(this).parents('.layui-form').first().find('.form-search-show-expand');
            $elem.attr('expand-show', '');
            $elem.removeClass('form-search-show-expand');
        } else {
            $(this).data('expand', true);
            $(this).html('展开 <i class="layui-icon layui-icon-down"></i>');
            $(this).parents('.layui-form').first().find('[expand-show]').addClass('form-search-show-expand');
        }
    });
    exports('admin', admin);
});
